#include "paramsset.h"
#include "router/systemManager/paramsSet/EditConfigDlg.h"



ParamsSet::ParamsSet(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_setParam_hideSearch->setIcon(pix);
    ui->btn_setParam_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_setParam_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_setParam_refresh->setIcon(freshPix.scaled(25,25));
    ui->lineEdit_setParam_gotoPage->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*")));

    init();

    //隐藏搜索
    connect(ui->btn_setParam_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_36->setHidden(!ui->widget_36->isHidden());
    });
    //下一页
    connect(ui->btn_setParam_next,&QPushButton::clicked,this,[=](){
        ui->btn_setParam_next->setEnabled(0);
        currentPage ++;
        getList();
        initTableWidget();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_setParam_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_setParam_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTableWidget();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_setParam_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_setParam_gotoPage->text().toInt();
        ui->lineEdit_setParam_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_setParam_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_setParam_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTableWidget();
        initPageInfo();
    });
    //每页大小
    connect(ui->comboBox_setParam_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
    //重置
    connect(ui->btn_setParam_reset,&QPushButton::clicked,this,[=](){
        init();
    });
    //搜索
    connect(ui->btn_setParam_search,&QPushButton::clicked,this,[=](){
        getList();
        initTableWidget();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_setParam_refresh,&QPushButton::clicked,this,[=](){
        getList();
        initTableWidget();
        initPageInfo();
    });
    //增加
    connect(ui->btn_setParam_add,&QPushButton::clicked,this,[=](){
        EditConfigDlg e("0",dictList);
        connect(&e,&EditConfigDlg::success,this,[=](){
            getList();
            initTableWidget();
            initPageInfo();
        });
        e.exec();
    });
    //修改
    connect(ui->btn_setParam_modify,&QPushButton::clicked,this,[=](){
        int index = ui->tableWidget_setParam->currentRow();
        if(index < 0) return;
        QString id = ui->tableWidget_setParam->item(index,0)->text();
        EditConfigDlg e(id,dictList);
        connect(&e,&EditConfigDlg::success,this,[=](){
            getList();
            initTableWidget();
            initPageInfo();
        });
        e.exec();
    });
    //批量删除
    connect(ui->btn_setParam_delete,SIGNAL(clicked()),this,SLOT(deleteByIds()));
    //导出
    connect(ui->btn_setParam_export,&QPushButton::clicked,this,[=](){
        Utils utils;
        utils.exportExcel(ui->tableWidget_setParam,"参数设置表格");
    });
    //刷新缓存
    connect(ui->btn_setParam_refreshCache,&QPushButton::clicked,this,[=](){
        QByteArray bytes = paramsSetApi.refreshCache()->readAll().data();
        if(bytes.isEmpty()){
            QMessageBox::warning(0,"提示","服务器连接失败");
            return;
        }
        QJsonObject obj = QJsonDocument::fromJson(bytes).object();
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
    });
}

void ParamsSet::init()
{
    getDict();
    initSearchArea();
    pageSize = 10;
    total = 0;
    currentPage = 1;
    getList();
    initTableWidget();
    initPageInfo();
}

void ParamsSet::getList()
{
    sysConfigList.clear();
    QNetworkReply *r = paramsSetApi.list(currentPage,pageSize,ui->lineEdit_setParam_paramName->text(),
                                         ui->lineEdit_setParam_paramKeyName->text(),
                                         ui->comboBox_setParam_systemBuiltIn->currentData().value<QString>(),
                                         ui->dateEdit_setParam_startTime->text(),
                                         ui->dateEdit_setParam_endTime->text());
    QByteArray bytes = r->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(0,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(200 != obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        return;
    }
    total = obj.value("total").toInt();
    QJsonArray rows = obj.value("rows").toArray();
    for(int i = 0;i< rows.size();i++){
        SysConfig *c = SysConfig::toSysConfig(rows.at(i).toObject());
        sysConfigList.append(*c);
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_setParam_count->setText("共"+QString::number(total)+"条");
}

void ParamsSet::getDict()
{
    dictList.clear();
    QNetworkReply *r = paramsSetApi.sys_yes_no();
    QByteArray bytes = r->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(0,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(200 != obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        return;
    }
    QJsonArray rows = obj.value("data").toArray();
    for(int i = 0;i< rows.size();i++){
        DictData d = DictData::toDictData(rows.at(i).toObject());
        dictList.append(d);
    }
}

void ParamsSet::initTableWidget()
{
    ui->tableWidget_setParam->setSortingEnabled(0);
    ui->tableWidget_setParam->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_setParam->clear();
    QStringList columnHeader;
    columnHeader << "主键" << "参数名称" << "参数键名" << "参数键值" << "系统内置" << "备注" << "操作";
    ui->tableWidget_setParam->setColumnCount(columnHeader.size());
    ui->tableWidget_setParam->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_setParam->setRowCount(sysConfigList.size());
    ui->tableWidget_setParam->setColumnWidth(1,220);
    ui->tableWidget_setParam->setColumnWidth(2,215);
    ui->tableWidget_setParam->setColumnWidth(3,110);
    ui->tableWidget_setParam->setColumnWidth(4,60);
    ui->tableWidget_setParam->setColumnWidth(5,180);
    ui->tableWidget_setParam->setColumnWidth(6,170);
    for(int i = 0;i< sysConfigList.size();i++){
        ui->tableWidget_setParam->setRowHeight(i,38);
        ui->tableWidget_setParam->setItem(i,0,new QTableWidgetItem(QString::number(sysConfigList.at(i).configId)));
        ui->tableWidget_setParam->setItem(i,1,new QTableWidgetItem(sysConfigList.at(i).configName));
        ui->tableWidget_setParam->setItem(i,2,new QTableWidgetItem(sysConfigList.at(i).configKey));
        ui->tableWidget_setParam->setItem(i,3,new QTableWidgetItem(sysConfigList.at(i).configValue));
        QLabel *label = new QLabel();
        for (int j = 0; j < dictList.size(); ++j) {
            if(sysConfigList.at(i).configType == dictList.at(j).dictValue){
                label->setText(dictList.at(j).dictLabel);
                label->setStyleSheet(utils.backShowStyle[dictList.at(j).listClass]);
                break;
            }
        }
        label->setFixedSize(46,20);
        label->setAlignment(Qt::AlignCenter);
        QWidget *widget = new QWidget();
        QHBoxLayout* hLayout = new QHBoxLayout(widget);
        // 设置QLabel的对齐方式为居中
        label->setAlignment(Qt::AlignCenter);
        // 将QLabel添加到QHBoxLayout和QVBoxLayout
        hLayout->addWidget(label);
        ui->tableWidget_setParam->setCellWidget(i,4,widget);

        ui->tableWidget_setParam->setItem(i,5,new QTableWidgetItem(sysConfigList.at(i).remark));
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnUpdate = new QPushButton;
        QPushButton *btnDelete = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            int flag  = QMessageBox::question(0,"提示","确定删除该项吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                QNetworkReply *r = paramsSetApi.deleteItems(QString::number(sysConfigList.at(i).configId));
                QByteArray bytes = r->readAll().data();
                if(bytes.isEmpty()){
                    QMessageBox::warning(0,"提示","服务器连接失败");
                    return;
                }
                QJsonObject obj = QJsonDocument::fromJson(bytes).object();
                QMessageBox::warning(0,"提示",obj.value("msg").toString());
                if(200 != obj.value("code").toInt()){
                    return;
                }
                getList();
                initTableWidget();
                initPageInfo();
            }
        });
        connect(btnUpdate,&QPushButton::clicked,this,[=](){
            EditConfigDlg editConfigdLG(QString::number(sysConfigList.at(i).configId),dictList);
            connect(&editConfigdLG,&EditConfigDlg::success,this,[=](){
                getList();
                initTableWidget();
                initPageInfo();
            });
            editConfigdLG.exec();
        });
        btnDelete->setText("🗑删除");
        btnDelete->setFixedSize(80,35);
        btnUpdate->setText("🖍修改");
        btnUpdate->setFixedSize(80,35);
        btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
        btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");

        tmp_layout->addWidget(btnUpdate);
        tmp_layout->addWidget(btnDelete);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget_setParam->setCellWidget(i,6,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_setParam->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_setParam->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_setParam->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_setParam->setSortingEnabled(1);
}

void ParamsSet::initSearchArea()
{
    ui->lineEdit_setParam_paramName->clear();
    ui->lineEdit_setParam_paramKeyName->clear();
    ui->comboBox_setParam_systemBuiltIn->clear();
    ui->comboBox_setParam_systemBuiltIn->addItem("");
    for(int i = 0;i< dictList.size();i++){
        ui->comboBox_setParam_systemBuiltIn->addItem(dictList.at(i).dictLabel,dictList.at(i).dictValue);
    }
    ui->dateEdit_setParam_startTime->setDate(QDate(2000,1,1));
    ui->dateEdit_setParam_endTime->setDate(QDate(2000,1,1));
}

void ParamsSet::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_setParam_pervious->setEnabled(0);
    }else{
        ui->btn_setParam_pervious->setEnabled(1);
    }
    ui->label_setParam_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_setParam_next->setEnabled(0);
    }else{
        ui->btn_setParam_next->setEnabled(1);
    }
}

void ParamsSet::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTableWidget();
    initPageInfo();
}

void ParamsSet::deleteByIds()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_setParam->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 6;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget_setParam->row(items.at(i * 6));
        if(i != rowCount - 1){
            ids += ui->tableWidget_setParam->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget_setParam->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选用户吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QNetworkReply *r = paramsSetApi.deleteItems(ids);
    QByteArray bytes = r->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(0,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::warning(0,"提示",obj.value("msg").toString());
    if(200 != obj.value("code").toInt()){
        return;
    }
    getList();
    initTableWidget();
    initPageInfo();
}

